package server.utils;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.catalina.mapper.Context;
import server.catalina.mapper.Wrapper;
import server.classloder.MyClassLoader;
import server.servlet.HttpServlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @Author: Dengxh
 * @Date: 2020/12/29 0:27
 * @Description:
 */
public class ReadWebXml {
    /**
     *  解析某个应用的web.xml文件，然后封装到Wrapper的servletMap中
     */
    public static Context readWebXml(String  webAppPath){
        String webXmlAbsolutePath = webAppPath+"/web.xml";
        System.out.println("开始加载Context");
        Context context = new Context(webAppPath);
        try {
            InputStream inputStream = new FileInputStream(new File(webXmlAbsolutePath));
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(inputStream);
            //根元素
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//servlet");

            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);

                Element servletNameElement =(Element)element.selectSingleNode("servlet-name");
                String servletName = servletNameElement.getStringValue();
                Element servletClassElement =(Element)element.selectSingleNode("servlet-class");
                String servletClass = servletClassElement.getStringValue();

                Element servletMapping =(Element)rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']'");
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                MyClassLoader myClassLoader = new MyClassLoader(webAppPath);
                Class<?> aClass = myClassLoader.loadClass(servletClass);

                Wrapper wrapper = new Wrapper((HttpServlet) aClass.getDeclaredConstructor().newInstance());

                context.setWrapperMap(urlPattern,wrapper);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return context;
    }


}
